<template>
  <div class="exam-generation-container">
    <!--    <h1 class="page-title">考核内容生成</h1>-->

    <a-row :gutter="24">
      <a-col :span="16">
        <!-- 左侧内容区 -->
        <a-card title="考核内容设置" class="section-card">
          <a-form layout="vertical">
            <a-form-item label="考核内容来源">
              <a-radio-group v-model:value="contentSourceType">
                <a-radio value="knowledgePoint">特定知识点</a-radio>
                <a-radio value="material">提供的材料</a-radio>
                <a-radio value="syllabus">已有的教学大纲</a-radio>
              </a-radio-group>
            </a-form-item>

            <!-- 知识点选择 -->
            <a-form-item v-if="contentSourceType === 'knowledgePoint'" label="知识点选择">
              <a-input v-model:value="formState.knowledgePoint" placeholder="请输入考核的知识点" />
            </a-form-item>

            <!-- 材料上传 -->
            <a-form-item v-if="contentSourceType === 'material'" label="材料上传">
              <a-upload-dragger
                name="file"
                :multiple="false"
                :before-upload="beforeUpload"
                :custom-request="handleUpload"
                :show-upload-list="false"
              >
                <p class="ant-upload-drag-icon">
                  <inbox-outlined></inbox-outlined>
                </p>
                <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
                <p class="ant-upload-hint">支持单个文件上传，可上传Word、PDF、TXT等格式文件</p>
              </a-upload-dragger>
            </a-form-item>

            <!-- 教学大纲 -->
            <a-form-item v-if="contentSourceType === 'syllabus'" label="教学大纲选择">
              <a-select
                placeholder="请选择教学大纲"
                style="width: 100%"
                :options="syllabusOptions"
                v-model:value="formState.generateTeachId"
              ></a-select>
            </a-form-item>

            <a-form-item label="题目数量">
              <a-row :gutter="16">
                <a-col :span="8" v-for="(exam, index) in questionList" :key="index">
                  <a-form-item :label="exam.type" :colon="false">
                    <a-input-number
                      :min="0"
                      :max="5"
                      v-model:value="exam.count"
                      style="width: 100%"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form-item>

            <a-form-item label="题目难度">
              <a-rate v-model:value="difficultyLevel" :count="5" allow-half />
              <span class="difficulty-text">
                {{ getLevelText(difficultyLevel) }}
              </span>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="generateExam"> 生成考核内容 </a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>

      <a-col :span="8">
        <!-- 右侧辅助区 -->
        <a-card title="历史考核" class="section-card">
          <a-list size="small" :data-source="historyList">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta
                  :title="item?.title"
                  :description="`${formatDate(item.createTime)} · ${item?.knowledgePoint}`"
                >
                  <template #avatar>
                    <a-avatar :style="{ backgroundColor: getColorById(item.id) }">
                      {{ item.title?.charAt(0) }}
                    </a-avatar>
                  </template>
                </a-list-item-meta>
                <template #extra>
                  <a-tag :color="getStatusColor(getStatusLabel(item.status))" class="status-tag">
                    {{ getStatusLabel(item.status) }}
                  </a-tag>
                </template>
                <template #actions>
                  <a-space>
                    <a-button
                      type="primary"
                      size="small"
                      :disabled="isButtonDisabled(item.status)"
                      @click="viewOrEdit(item.id)"
                      ref="editBtnRef"
                      >查看并编辑</a-button
                    >
                  </a-space>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, onBeforeUnmount } from 'vue'
import { InboxOutlined } from '@ant-design/icons-vue'
import { listGenerateTeachVoByPage } from '@/api/generateTeachController'
import { message, type UploadProps } from 'ant-design-vue'
import router from '@/router'
import { useLoginUserStore } from '@/store/user'
import { getLevelText } from '@/utils/enums/ExamDifficultyLevelEnum'
import {
  addGenerateExam,
  listGenerateExamVoByPage,

} from '@/api/generateExamController'
import dayjs from 'dayjs'
import { getStatusLabel, Status } from '@/utils/enums/GenerateTeachEnum'
import { uploadReferenceFile } from '@/api/generateExercisesController'
//格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 题目难度
const difficultyLevel = ref(3)
// 考核内容来源类型
const contentSourceType = ref('knowledgePoint')
//上传文件的响应对象
const currentFileInfo = ref<API.UploadReturnVO>()
//当前用户
const loginUser = useLoginUserStore()
const questionList = reactive<API.Exam[]>([
  { type: '选择题', count: 2 },
  { type: '填空题', count: 2 },
  { type: '判断题', count: 1 },
  { type: '程序题', count: 2 },
  { type: '简答题', count: 1 },
  { type: '综合题', count: 0 },
])
const formState = reactive<API.AddGenerateExamRequest>({
  teacherId: loginUser.loginUser.id,
  knowledgePoint: '',
  generateTeachId:'',
  difficultyLevel: getLevelText(difficultyLevel.value),
  exams: questionList,
  id: currentFileInfo.value?.id,
})

const dataList = ref<API.GenerateTeachVO[]>([])
//搜索条件 复用分页查询的接口
const searchParams = reactive<API.GenerateTeachQueryDTO>({
  current: 1,
  pageSize: 5, //固定只能展示3个数据
})
//页面加载自动获取数据
onMounted(() => {
  fetchData()
  fetchHistoryData()
})
const fetchData = async () => {
  try {
    const res = await listGenerateTeachVoByPage({
      ...searchParams,
    })
    if (res.data.data && res.data.code === 0) {
      dataList.value = res.data.data.records ?? []
    } else {
      message.error('获取最近备课列表失败' + res.data.msg)
    }
  } catch (e) {
    message.error('获取最近备课列表失败' + e)
  }
}
// 计算属性 得到 教学大纲选项
const syllabusOptions = computed(() => {
  return dataList.value
    .filter((item) => item.id !== undefined && item.title !== undefined)
    .map((item) => ({
      // value:`sy${item.id}`,
      value: item.id,
      label: item.title,
    }))
})

const getHistoryParams = reactive<API.GenerateExamQueryDTO>({
  current: 1,
  pageSize: 5, //固定只能展示5个数据
})
//历史记录列表
const historyList = ref<API.GenerateExamPageVO[]>([])

const fetchHistoryData = async () => {
  try {
    const res = await listGenerateExamVoByPage({
      ...getHistoryParams,
    })
    if (res.data.data && res.data.code === 0) {
      historyList.value = res.data.data.records ?? []
    } else {
      message.error('获取历史考核列表失败' + res.data.msg)
    }
  } catch (e) {
    message.error('获取历史考核列表失败' + e)
  }
}

//定义颜色
const colors = ['#1890ff', '#52c41a', '#722ed1'] // 预定义颜色列表
// 接收一个数字，根据数字 % 3 的结果返回对应的颜色
const getColorById = (num: number) => {
  const index = num % 3 // 计算下标
  return colors[index] // 返回对应的颜色
}
// 判断按钮是否需要禁用
const isButtonDisabled = (status: number): boolean => {
  return (
    status === Status.Failed || // 失败
    status === Status.Generating || // 生成中
    status === Status.Pending // 等待中
  )
}
// 根据状态获取标签颜色
const getStatusColor = (status: string) => {
  const statusColors: Record<string, string> = {
    已发布: 'green',
    草稿: 'orange',
    等待中: 'blue',
    下架: 'purple',
    生成中: 'gray',
    失败: 'red',
  }
  return statusColors[status] || 'default'
}

//查看或编辑
const viewOrEdit = (id: number) => {
  router.push(`/teacher/exam_generation/edit/${id}`)
}

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isValidType =
    file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || // docx
    file.type === 'application/msword' || // doc
    file.type === 'application/pdf' || // pdf
    file.type === 'text/markdown' // md;
  if (!isValidType) {
    message.error('只能上传.docx, .pdf, .md 等格式文件!')
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('图片大小不能超过 10MB!')
  }

  return isValidType && isLt10M
}

//处理上传
const handleUpload = async ({ file }: any) => {
  // 保存上传的文件信息

  const res = await uploadReferenceFile(file)
  try {
    if (res.data.data && res.data.code === 0) {
      message.success('文件上传成功')
      currentFileInfo.value = res.data.data
    } else {
      message.error('文件上传失败,' + res.data.msg)
    }
  } catch (e) {
    message.error('文件上传失败,' + res.data.msg)
  }
}

// 生成考核内容
const generateExam = async () => {
  if (formState.knowledgePoint === '' && !formState.generateTeachId && !formState.id) {
    message.warning('请选择考核内容来源，并确保其不为空')
    return
  }
  //TODO 生成的逻辑
  try {
    const res = await addGenerateExam(formState)
    if (res.data.data && res.data.code === 0) {
      message.success('考核正在生成中...')
    } else {
      message.error('考核生成失败，请稍后重试')
    }
  } catch (e) {
    message.error('考核生成失败，请稍后重试')
  }
  // console.log(formState)
}
</script>

<style scoped>
.exam-generation-container {
  padding: 24px;
  background: url('@/assets/BackGround/exambg.png') no-repeat center center;
  background-size: cover;
  min-height: 100vh;
  position: relative;
  animation: fadeIn 0.8s ease-out;
}

.exam-generation-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.65);
  z-index: 0;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInDown {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

.page-title {
  font-size: 24px;
  margin-bottom: 24px;
  color: var(--primary-color);
  animation: slideInDown 0.8s ease-out 0.2s both;
  z-index: 1;
}

.section-card {
  margin-bottom: 24px;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  animation: slideInUp 0.8s ease-out 0.6s both;
  z-index: 1;
}

.section-card:hover {
  box-shadow: 0 16px 48px rgba(255, 107, 107, 0.2);
  transform: translateY(-4px);
  background: rgba(255, 255, 255, 0.98);
}

.difficulty-text {
  margin-left: 10px;
  color: rgba(0, 0, 0, 0.65);
  font-weight: 500;
  animation: slideInRight 0.8s ease-out 1s both;
  z-index: 1;
}

/* 表单元素样式优化 */
:deep(.ant-form-item-label > label) {
  font-weight: 600;
  color: #333;
  animation: slideInLeft 0.8s ease-out 0.8s both;
  z-index: 1;
}

:deep(.ant-input),
:deep(.ant-input-affix-wrapper) {
  border-radius: 12px;
  border: 2px solid #e8e8e8;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
}

:deep(.ant-input:focus),
:deep(.ant-input-affix-wrapper:focus) {
  border-color: #ff6b6b;
  box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.1);
  transform: translateY(-2px);
}

:deep(.ant-select) {
  border-radius: 12px;
}

:deep(.ant-select-focused .ant-select-selector) {
  border-color: #ff6b6b !important;
  box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.1) !important;
}

:deep(.ant-radio-group) {
  animation: slideInUp 0.8s ease-out 1.2s both;
  z-index: 1;
}

:deep(.ant-radio-wrapper) {
  transition: all 0.3s ease;
  padding: 8px 12px;
  border-radius: 8px;
  margin-right: 16px;
}

:deep(.ant-radio-wrapper:hover) {
  background: rgba(255, 107, 107, 0.05);
  transform: translateY(-2px);
}

:deep(.ant-rate) {
  animation: slideInUp 0.8s ease-out 1.4s both;
  z-index: 1;
}

:deep(.ant-rate-star) {
  transition: all 0.3s ease;
}

:deep(.ant-rate-star:hover) {
  transform: scale(1.2);
}

/* 生成按钮样式 */
:deep(.ant-btn-primary) {
  background: linear-gradient(45deg, #ff6b6b, #ffa726);
  border: none;
  border-radius: 12px;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  box-shadow: 0 4px 16px rgba(255, 107, 107, 0.3);
  position: relative;
  overflow: hidden;
  animation: slideInUp 0.8s ease-out 1.6s both;
  z-index: 1;
}

:deep(.ant-btn-primary::before) {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.6s;
}

:deep(.ant-btn-primary:hover) {
  background: linear-gradient(45deg, #ff5252, #ff9800);
  transform: translateY(-3px) scale(1.02);
  box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4);
}

:deep(.ant-btn-primary:hover::before) {
  left: 100%;
}

:deep(.ant-btn-primary:active) {
  transform: translateY(-1px) scale(1.01);
}

/* 历史记录列表样式 */
:deep(.ant-list-item) {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(8px);
  border-radius: 12px;
  margin-bottom: 12px;
  padding: 16px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  animation: slideInRight 0.8s ease-out 1.8s both;
  z-index: 1;
}

:deep(.ant-list-item:hover) {
  background: rgba(255, 255, 255, 0.95);
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(255, 107, 107, 0.15);
}

:deep(.ant-avatar) {
  animation: pulse 2s ease-in-out infinite;
}

:deep(.ant-tag) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.ant-tag:hover) {
  transform: scale(1.05);
}

/* 上传区域样式 */
:deep(.ant-upload-drag) {
  background: linear-gradient(135deg, rgba(255, 107, 107, 0.05), rgba(255, 159, 67, 0.05));
  backdrop-filter: blur(8px);
  border: 2px dashed rgba(255, 107, 107, 0.3);
  border-radius: 16px;
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  animation: slideInUp 0.8s ease-out 1.2s both;
  z-index: 1;
}

:deep(.ant-upload-drag:hover) {
  border-color: #ff6b6b;
  background: linear-gradient(135deg, rgba(255, 107, 107, 0.1), rgba(255, 159, 67, 0.1));
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(255, 107, 107, 0.15);
}

:deep(.ant-upload-drag-icon) {
  color: #ff6b6b;
  font-size: 48px;
  animation: float 3s ease-in-out infinite;
}

:deep(.ant-upload-text) {
  color: #333;
  font-weight: 600;
  font-size: 16px;
}

:deep(.ant-upload-hint) {
  color: #666;
  font-size: 14px;
}

/* 题目数量输入框样式 */
:deep(.ant-input-number) {
  border-radius: 8px;
  border: 2px solid #e8e8e8;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
}

:deep(.ant-input-number:hover) {
  border-color: #ff6b6b;
  transform: translateY(-2px);
}

:deep(.ant-input-number:focus) {
  border-color: #ff6b6b;
  box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.1);
}

/* 题目类型标签样式 */
:deep(.ant-form-item-label > label) {
  font-weight: 600;
  color: #333;
  position: relative;
  padding-left: 12px;
}

:deep(.ant-form-item-label > label::before) {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background: linear-gradient(45deg, #ff6b6b, #ffa726);
  border-radius: 2px;
}

.question-section {
  margin-bottom: 24px;
  animation: slideInUp 0.8s ease-out 1.4s both;
  z-index: 1;
}

.question-list {
  margin-top: 16px;
}

.question-item {
  margin-bottom: 16px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(8px);
  border-radius: 12px;
  padding: 16px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.question-item:hover {
  background: rgba(255, 255, 255, 0.95);
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.1);
}

.question-options {
  margin-top: 8px;
  margin-left: 24px;
}

.answer-section {
  margin-bottom: 24px;
}

.answer-list {
  margin-top: 8px;
}

.answer-item {
  margin-bottom: 8px;
}

.code-answer {
  background-color: rgba(245, 245, 245, 0.9);
  backdrop-filter: blur(5px);
  padding: 12px;
  border-radius: 8px;
  font-family: 'Courier New', Courier, monospace;
  white-space: pre-wrap;
  word-wrap: break-word;
  border: 1px solid rgba(255, 107, 107, 0.2);
}

.action-buttons {
  margin-top: 24px;
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .exam-generation-container {
    padding: 16px;
  }

  .section-card {
    border-radius: 12px;
  }

  :deep(.ant-list-item) {
    padding: 12px;
  }
}

@media (max-width: 768px) {
  .exam-generation-container {
    padding: 8px;
  }

  .section-card {
    border-radius: 8px;
  }

  :deep(.ant-upload-drag) {
    border-radius: 12px;
  }

  :deep(.ant-btn-primary) {
    height: 40px;
    font-size: 14px;
  }
}

/* 状态标签动画 */
.status-tag {
  animation: pulse 2s ease-in-out infinite;
}

/* 卡片标题样式 */
:deep(.ant-card-head-title) {
  font-size: 18px;
  font-weight: 700;
  background: linear-gradient(45deg, #ff6b6b, #ffa726);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  animation: slideInDown 0.8s ease-out 0.4s both;
  z-index: 1;
}

/* 列表项元数据样式 */
:deep(.ant-list-item-meta-title) {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

:deep(.ant-list-item-meta-description) {
  color: #666;
  font-size: 12px;
}

/* 按钮组样式 */
:deep(.ant-space) {
  animation: slideInRight 0.8s ease-out 2s both;
  z-index: 1;
}

:deep(.ant-btn) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.ant-btn:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 输入数字组件样式 */
:deep(.ant-input-number-handler-wrap) {
  border-radius: 0 8px 8px 0;
}

:deep(.ant-input-number-handler) {
  transition: all 0.3s ease;
}

:deep(.ant-input-number-handler:hover) {
  background: rgba(255, 107, 107, 0.1);
}

/* 选择器下拉样式 */
:deep(.ant-select-dropdown) {
  border-radius: 12px;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

:deep(.ant-select-item) {
  border-radius: 8px;
  margin: 2px 8px;
  transition: all 0.3s ease;
}

:deep(.ant-select-item:hover) {
  background: rgba(255, 107, 107, 0.1);
  transform: translateX(4px);
}

:deep(.ant-select-item-option-selected) {
  background: linear-gradient(45deg, rgba(255, 107, 107, 0.2), rgba(255, 167, 38, 0.2));
}
</style>
